package org.apache.celestial.connector;

import org.springframework.util.Assert;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Properties;
import java.util.stream.Stream;

public class SocketConnector<T> implements IConnector<T> {

    private  static ServerSocket serverSocket;

    @Override
    public void init(Properties props) throws IOException {
        Assert.notNull(props.get(ConnectorConstants.SOCKET_PORT),"please provide the listener port!");
        serverSocket = new ServerSocket((Integer) props.get(ConnectorConstants.SOCKET_PORT));
    }

    @Override
    public T getData() {
        Socket socket = null;
        InputStream is = null;
        InputStreamReader isr = null;
        BufferedReader br = null;
        StringBuilder sb = new StringBuilder();
        try {
            socket = serverSocket.accept();

            is  = socket.getInputStream();
            isr = new InputStreamReader(is);
            br = new BufferedReader(isr);

            String info = null;
            while ((info = br.readLine()) != null) {
//                System.out.println("Hello,我是服务器，客户端说：" + info);
                sb.append(info);
            }
            socket.shutdownInput();//关闭输入流
            br.close();
            isr.close();
            is.close();
            socket.close();

        } catch (IOException e) {
            e.printStackTrace();
        }finally {

        }
        return (T) sb.toString();
    }

}
